package com.xiaoshuo.fictionUtiles;

import com.xiaoshuo.fictionworm.entity.FictionList;
import com.xiaoshuo.fictionworm.entity.FictionPage;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

public class FictionSearchUtils {
    private String fictionName = null; //小说名字
    private String fictionURL = null; //小说界面url
    private List<String> tagChar = null; //标签删除内容
    private List<String> tagClassName = null; //标签className
    private List<String> tagAttrName = null; //标签属性名
    private String homePageUrl = "http://www.janpn.com"; //默认小说主页网址
    private String searchUrl = "http://www.janpn.com/search.php?q="; //默认搜索网址
    private String moreUrl = "&s=15947871991047423724"; //更多奇怪的字段
    private Map<String, String> headerMap = new HashMap<String, String>(); //头信息Map
    private String fictionSearchUrl = null; //小说搜索出来的路径

    private FictionList fictionList = null; //小说对象
    private Connection connection = null; //连接对象

    /**
     *
     * **/
    public FictionList wormFiction(String name) throws IOException {
        //设置小说名字
        fictionName = name; // 剑来
        //获取小说搜索路径
        fictionSearchUrl = jointSearchUrl(); // http://www.janpn.com/search.php?q=%E5%89%91%E6%9D%A5&s=15947871991047423724
        //建立连接获取连接对象
        connection = Jsoup.connect(fictionSearchUrl);
        //稍微伪装一下
        connection = pretendConnection(connection); //添加了一系列莫名其妙的头文件
        //请求获取Document
        Document document = connection.get();//这里拿到的是搜索页的所有东西
        //获取详情页的URL
        getFictionURL(document);
        //建立连接获取连接对象
        connection = Jsoup.connect(fictionURL);
        //稍微伪装一下
        connection = pretendConnection(connection); //添加了一系列莫名其妙的头文件
        Elements elementsByClass = connection.get().getElementsByClass("panel-chapterlist");//分割小说详情页拿出每一个A标签
        LinkedHashMap<String, String> catalog = getCatalog(elementsByClass);//这里拿到的对象就是 小说 章节：网址
        List<String> list = new ArrayList<String>();
        List<String> listName = new ArrayList<String>();
        Set<String> strings = catalog.keySet();
        fictionList = new FictionList();
        List<FictionPage> listPage = new ArrayList<>();
        fictionList.setFictionPages(listPage);
        for (String string : strings) {
            FictionPage fictionPage = new FictionPage();
            fictionPage.setFictionName(catalog.get(string));
            fictionPage.setFictionUrl(string);
            fictionList.getFictionPages().add(fictionPage);
           // list.add(string);
            //listName.add(catalog.get(string));
        }

       // fictionList.setListUrl(list);
        fictionList.setFictionName(fictionName);
        System.out.println(fictionList);//--------------------------------------
       // fictionList.setListName(listName);
        return fictionList;
    }

    public String getText(List<FictionPage> fictionPages, Integer integer) throws IOException {
       // String fictionUrl = list.getListUrl().get(integer - 1); //http://www.janpn.com/book/152/152272/31086853.html
        String fictionUrl1 = fictionPages.get(integer - 1).getFictionUrl();
       // Connection connect = Jsoup.connect(fictionUrl);
        Connection connect = Jsoup.connect(fictionUrl1);
        Connection connection = pretendConnection(connect);
        Document document = connection.get();
        Elements elementsByClass = document.getElementsByClass("panel-body");
        String html = elementsByClass.html();
       // String s = html.replaceAll("<br />", "");
        //String text = s.replaceAll("&nbsp;", "    ");//这就是小说主题 直接返回这个小说主题
        return html;
    }


    public FictionList wormFiction2(String name) throws IOException {
        //设置小说名字
        fictionName = name; // 剑来
        //获取小说搜索路径
        fictionSearchUrl = jointSearchUrl(); // http://www.janpn.com/search.php?q=%E5%89%91%E6%9D%A5&s=15947871991047423724
        //建立连接获取连接对象
        connection = Jsoup.connect(fictionSearchUrl);
        //稍微伪装一下
        connection = pretendConnection(connection); //添加了一系列莫名其妙的头文件
        //请求获取Document
        Document document = connection.get();//这里拿到的是搜索页的所有东西
        //获取详情页的URL
        List<String> fName = getAll(document);
        List<String> fictionURL = getFictionURL(document, fName);
        fictionList = new FictionList();
        List<FictionPage> listPage = new ArrayList<>();
        fictionList.setFictionPages(listPage);
        for (int i = 0; i < fName.size(); i++) {
            FictionPage fictionPage = new FictionPage();
            fictionPage.setFictionUrl(fictionURL.get(i));
            fictionPage.setFictionName(fName.get(i));
            fictionList.getFictionPages().add(fictionPage);
        }
        fictionList.setFictionName(fictionName);
        System.out.println(fictionList);//--------------------------------------
        // fictionList.setListName(listName);
        return fictionList;
    }
    public FictionList wormFiction3(String url) throws IOException {
        //建立连接获取连接对象
        System.out.println(fictionList);//--------------------------------------
        // fictionList.setListName(listName);
        return fictionList;
    }

    private List<String> getAll(Document document) {
        Elements shop = document.getElementsByClass("shop");
        String[] split = shop.toString().split("\"");
        List<String> fName = new ArrayList<String>();
        int k = 0;
        for (int i = 1; i < split.length;) {
            if (k == 0 ){
                fName.add(split[i]);
                i+=4;
                k=1;
            }else {
                i+=10;
                k=0;
            }
        }
        return fName;
    }


    /**
     * 默认为url搜索方式
     * 此处做两个方案
     * 1.自动拼接
     * 2.手动拼接返回set
     **/
    private String jointSearchUrl() {
        String code = null; //url编码 %FA
        try {
            code = URLEncoder.encode(fictionName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StringBuffer stringBuffer = new StringBuffer(searchUrl);
        stringBuffer.append(code).append(moreUrl); //http://www.janpn.com/search.php?q=code&s=15947871991047423724
        return stringBuffer.toString();
    }
    /**
     * 2.手动拼接返回
     * **/
//    public String jointSearchUrl(){}

    /**
     * 意思意思伪装一下
     **/
    private Connection pretendConnection(Connection connection) {
        //如果手动设置了头信息就用手动的
        if (headerMap.size() > 1) {
            Set<String> key = headerMap.keySet();
            for (String keyValue : key) {
                String value = headerMap.get(keyValue);
                connection.header(keyValue, value);
            }
        } else {
            //没有就默认加下面的
            connection
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36")
                    .header("Host", homePageUrl)
                    .header("Connection", "keep-alive")
                    .header("method", "GET")
                    .header("user-agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36")
                    .header("Referer", homePageUrl);
        }
        return connection;
    }

    /**
     * 获取小说详情页的URL
     * 发送请求获取搜索页之后使用 直接返回小说详情页URL
     * r:http://www.janpn.com/book/167/167392/
     **/
    private void getFictionURL(Document document) {
        //获取该Document中的 title为 小说名的a标签
        Elements elements = document.getElementsByAttributeValue("title", fictionName);
        //通过该标签获取具体的fictionUrl
        String href = elements.attr("href");
        fictionURL = homePageUrl + href;
    }


    private List<String> getFictionURL(Document document,List<String> list) {
        //获取该Document中的 title为 小说名的a标签
        List<String> url = new ArrayList<>();
        for (String s : list) {
            Elements elements = document.getElementsByAttributeValue("title", s);
            String href = elements.attr("href");
            url.add(homePageUrl + href);
        }

        //通过该标签获取具体的fictionUrl
        //fictionURL = homePageUrl + href;
        return url;
    }

    /**
     * 这里已经获取了
     * r:一个map集合 其key为小说真实页面的 网址  value为章节名称
     **/
    private LinkedHashMap<String, String> getCatalog(Elements elements) {
        //这里把 ul标签给我  返回是一个 a标签href+具体值的map集合
        Elements aTag = elements.select("a");//现在就是a标签的集合了
        LinkedHashMap<String, String> map = new LinkedHashMap();
        for (int i = 0; i < aTag.toArray().length; i++) {
            //循环A标签个数次数
            Element element = aTag.get(i);//这就是一个a标签
            String href = element.attr("href");//这是具体的小说页面的网址
            String html = element.html();//这是小说的标题
            map.put(addUrl(href), html);//这样就把具体的小说界面网址 及 章节名字配对了
        }
        return map;
    }

    private String addUrl(String newString) {
        return fictionURL + newString;
    }

    public String getFictionName() {
        return fictionName;
    }

    public FictionSearchUtils setFictionName(String fictionName) {
        this.fictionName = fictionName;
        return this;
    }

    public String getFictionURL() {
        return fictionURL;
    }

    public FictionSearchUtils setFictionURL(String fictionURL) {
        this.fictionURL = fictionURL;
        return this;
    }

    public List<String> getTagChar() {
        return tagChar;
    }

    public FictionSearchUtils setTagChar(List<String> tagChar) {
        this.tagChar = tagChar;
        return this;
    }

    public List<String> getTagClassName() {
        return tagClassName;
    }

    public FictionSearchUtils setTagClassName(List<String> tagClassName) {
        this.tagClassName = tagClassName;
        return this;
    }

    public List<String> getTagAttrName() {
        return tagAttrName;
    }

    public FictionSearchUtils setTagAttrName(List<String> tagAttrName) {
        this.tagAttrName = tagAttrName;
        return this;
    }

    public FictionList getFictionList() {
        return fictionList;
    }

    public Map<String, String> getHeaderMap() {
        return headerMap;
    }

    public FictionSearchUtils setHeaderMap(Map<String, String> headerMap) {
        this.headerMap = headerMap;
        return this;
    }

    public String getHomePageUrl() {
        return homePageUrl;
    }

    public FictionSearchUtils setHomePageUrl(String homePageUrl) {
        this.homePageUrl = homePageUrl;
        return this;
    }

    public String getSearchUrl() {
        return searchUrl;
    }

    public FictionSearchUtils setSearchUrl(String searchUrl) {
        this.searchUrl = searchUrl;
        return this;
    }

    public String getMoreUrl() {
        return moreUrl;
    }

    public FictionSearchUtils setMoreUrl(String moreUrl) {
        this.moreUrl = moreUrl;
        return this;
    }
}
